import { Component, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AppService } from '../../services/app.service';
import { RES_URL, SERVER_ADDR, REDIRECT_ADDR } from '../../app.component';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})
export class HomeComponent {
  isAuthenticated = false;
  checkSessionChanged$?: Observable<boolean>;
  checkSessionChanged?: boolean;

  public isLoggedIn = false;
  constructor(
    public _service: AppService,
    private _router: Router,
    @Inject(REDIRECT_ADDR) private redirectUrl: string,
    @Inject(SERVER_ADDR) private serverAddr: string){
      console.log(`Home with server Addr :${this.serverAddr}`)
    }

    ngOnInit() {
      console.log('Home inited');
      this.isLoggedIn = this._service.checkCredentials();
      const i = window.location.href.indexOf('code');
      if (!this.isLoggedIn && i == -1) {
        const loginUrl = this.serverAddr + `/oauth2/authorize?client_id=res-test1&response_type=code&scope=all&redirect_uri=${this.redirectUrl}`;
        console.log(`Old url :${window.location.href}`);
        console.log(`Home init to login url: ${loginUrl}`);

        window.location.href = loginUrl;
        // wechat需要用域名，resource admin可以用localhost
      } else if(!this.isLoggedIn && i != -1) {
        console.log(`to retrive token with ${window.location.href.substring(i + 5)}`);
        this._service.retrieveToken(window.location.href.substring(i + 5));
      } else {
        console.log('logged in home');
        this._router.navigateByUrl('/res-user');
      }
    }

    logout() {
      this._service.logout();
    }
}
